import {computed, reactive, ref} from "vue";
import {getMembersData} from "../../api/manage";
import {useStore} from "vuex";
import {FetchMembersDAT} from "../../types/responseTypes";

export function useMembers(){

    const memberListWrap = reactive<{memberList: FetchMembersDAT[]}>({
        memberList: []
    })

    const total = ref(0)

    const {state} = useStore()

    function initMemberList(page: number = 1, pageSize: number = 20, params?: Partial<{
        STUDENTNAME: string,
        STUDENTNO: string,
        TEACHERNAME: string
        TEACHERNO: string
        roleId: number,
        state: string
    }>){
        return new Promise((resolve, reject) => {
            getMembersData({
                CUSER_ID: '',
                STUDENTNAME: params?.STUDENTNAME || '',
                STUDENTNO: params?.STUDENTNO || '',
                TEACHERNAME: params?.TEACHERNAME || '',
                TEACHERNO: params?.TEACHERNO || '',
                USERNO: '',
                PHONENO: '',
                ROLE_ID: params?.roleId || 4,
                STATE: params?.state || '1',
                PAGEINDEX: page,
                PAGESIZE: pageSize,
                // OPERATOR_ID: '34'
                OPERATOR_ID: state.user.userInfo.CUSER_ID
            }).then(res => {
                if (res.ERROR[0].errcode == '0'){
                    memberListWrap.memberList = JSON.parse(JSON.stringify(res.DAT))
                    total.value = res.COUNT[0].NUM
                    resolve(null)
                }else {
                    uni.showToast({
                        title: res.ERROR[0].error,
                        icon: 'none',
                        mask: true
                    })
                    reject('err')
                }
            }).catch(err => {
                uni.showToast({
                    title: '获取列表失败',
                    icon: 'error',
                    mask: true
                })
                reject('err')
            })
        })
    }

    return {
        memberList: computed(() => memberListWrap.memberList),
        total,
        initMemberList
    }
}
